package com.wt.struggle.goodbye.user.activity

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Message
import android.support.v4.app.ActivityCompat
import com.wt.struggle.goodbye.MainActivity
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.Config
import com.wt.struggle.goodbye.base.ProActivity
import com.wt.struggle.goodbye.base.Send
import com.wt.struggle.goodbye.base.Share
import com.wt.struggle.goodbye.db.DbUtil
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.ProUserInfo
import com.xin.lv.yang.utils.net.Time
import kotlinx.android.synthetic.main.head.*
import kotlinx.android.synthetic.main.register_or_forget_layout.*
import org.json.JSONObject

class RegisterActivity : ProActivity() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {

        when (what) {
            2345 -> {
                val num = arg1
                if (num > 0) {
                    btRegisterGetYan.text = "$num S"
                } else {
                    btRegisterGetYan.text = "重新获取"
                    btRegisterGetYan.isClickable = true
                }
            }

            Send.SEND_YAN_CODE -> {

                if (netInfo.code == Config.SUCCESS) {
                    showToastShort("验证码发送成功，请注意查收。")

                }

            }

            Send.REGISTER -> {
                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {
                    showToastShort("注册成功")
                    login()
                } else {
                    showToastShort("注册失败，请重新提交。")
                }
            }

            Send.LOGIN -> {

                removeLoadDialog()

                if (netInfo.code == Config.SUCCESS) {

                    showToastShort("登录成功")

                    val jsonObject = JSONObject(netInfo.dataResult)
                    val token = jsonObject.optString("token")
                    val uid = jsonObject.optInt("uid")

                    Share.saveToken(this@RegisterActivity, token)
                    Share.saveUid(this@RegisterActivity, uid)

                    val userInfo = ProUserInfo()

                    val account = etRegisterPhone.text.toString()
                    userInfo.account = account
                    userInfo.pwd = etRegisterPwd.text.toString()
                    Share.saveAccount(this, account)

                    dbUtil!!.addAccount(userInfo)

                    startActivity(Intent(this, MainActivity::class.java))

                    finish()

                } else {
                    showToastShort(netInfo.dataResult!!)
                }
            }
        }
    }

    /**
     * 登录
     */
    private fun login() {
        val phone = etRegisterPhone.text.toString()
        val pwd = etRegisterPwd.text.toString()
        send!!.loginByPwd(phone, pwd, getImei(this), handler!!)
        showLoadDialog("登录中")

    }

    var dbUtil: DbUtil? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.register_or_forget_layout)
        tvTitle.text = "快速注册"
        initClick()
        dbUtil = DbUtil(this)
    }

    private fun initClick() {
        imageBack.setOnClickListener {
            finish()
        }

        btRegisterGetYan.setOnClickListener {
            registerCode()
        }

        btRegister.setOnClickListener {

            val code = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE)
            if (code == PackageManager.PERMISSION_GRANTED) {
                register()
            } else {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE), 999)
            }

        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 999) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                register()
            } else {
                showToastShort("请检查获取手机状态权限")
            }
        }
    }

    private fun register() {
        val phone = etRegisterPhone.text.toString()
        val yanCode = etRegisterYan.text.toString()
        val pwd = etRegisterPwd.text.toString()
        val pwdAgain = etRegisterPwdAgain.text.toString()

        when {
            phone == "" -> showToastShort("请输入电话号码")
            yanCode == "" -> showToastShort("请输入获取的短信验证码")
            pwd == "" -> showToastShort("请输入密码")
            pwdAgain == "" -> showToastShort("请确认密码")
            pwd.toUpperCase() != pwdAgain.toUpperCase() -> showToastShort("两次密码输入不一致")
            else -> {
                send!!.register(phone, yanCode, pwd, getImei(this), handler)
                showLoadDialog()
            }
        }

    }


    /**
     * 获取注册验证码
     */
    private fun registerCode() {
        val phone = etRegisterPhone.text.toString()
        if (phone != "") {

            btRegisterGetYan.isClickable = false
            Time(60, 2345, handler).start()

            send!!.sendYan(phone, 1, handler!!)

        } else {
            showToastShort("请输入电话号码")
        }


    }
}